package org.maxgroundstation.groundstation.comm.service.echo;

import javax.swing.SwingUtilities;

import org.maxgroundstation.groundstation.comm.service.Service;
import org.maxgroundstation.groundstation.comm.service.ServiceCommunication;
import org.maxgroundstation.groundstation.comm.service.ServiceDataFrame;
import org.maxgroundstation.groundstation.comm.service.ServiceUtil;

/**
 * The echo service.
 * @author Scott Davis
 * 
 * Copyright (C) 2010  Scott Davis
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
public class EchoService extends Service implements Runnable {

	// Static members
	public static final String SERVICE_ID = ServiceUtil.getServiceID("__echo");
	public static final String TYPE = "echo";
	public static final String PING = "ping";
	
	// Service event type.
	public static final String PING_UPDATE = "ping update";
	
	// Length of alive thread sleep time (milliseconds).
    private static final long SLEEP_TIME = 1000L;
    
    // Ping timeout in milliseconds.
    public static final Double PING_TIMEOUT = 5000D;
    
    // Data members
    private Thread pingThread;
    private boolean run;
    private double pingStartTime;
    private double pingLatencyUDP;
    private double pingLatencyTCP;
    private boolean completedPingUDP;
    private boolean completedPingTCP;
    private boolean noReturnUDP;
    private boolean noReturnTCP;
	
	/**
	 * Constructor
	 * @param comm the service communication.
	 */
	public EchoService(ServiceCommunication comm) {
		// Use Service constructor.
		super(comm);
		
		// Initialize data members.
		pingStartTime = 0D;
		pingLatencyUDP = 0D;
		pingLatencyTCP = 0D;
		completedPingUDP = false;
		completedPingTCP = false;
		noReturnUDP = false;
		noReturnTCP = false;
	}
	
	@Override
	public String getID() {
		return SERVICE_ID;
	}
	
	@Override
	public boolean isSubscribable() {
		return false;
	}
	
	@Override
	public void initialize() {
		// Start ping thread.
		start();
	}
	
	@Override
	public void closeDown() {
	    super.closeDown();
	    
		// Stop ping thread.
		run = false;
	}
	
	@Override
	public void handleResponse(ServiceDataFrame dataFrame) {
		String echoResponse = dataFrame.getDataString();
		if (PING.equals(echoResponse)) {
			double currentTime = (double) System.nanoTime() / 1000000D;
			
			if (dataFrame.getCommType() == ServiceCommunication.UDP) {
				pingLatencyUDP = currentTime - pingStartTime;
				completedPingUDP = true;
				noReturnUDP = false;
				//System.out.println("UDP Ping latency: " + (int) Math.round(pingLatencyUDP) + " ms");
			}
			else {
				pingLatencyTCP = currentTime - pingStartTime;
				completedPingTCP = true;
				noReturnTCP = false;
				//System.out.println("TCP Ping latency: " + (int) Math.round(pingLatencyTCP) + " ms");
			}
			
			SwingUtilities.invokeLater(new Runnable() {
				@Override
				public void run() {
				    fireServiceEvent(PING_UPDATE);
				}
			});
		}
		else {
			System.err.println("Invalid ping response: '" + echoResponse + "'");
		}
	}

	@Override
	public boolean isDefaultService() {
		return true;
	}
	
	/**
	 * Gets the current UDP ping latency.
	 * @return latency (ms).
	 */
	public double getUDPPingLatency() {
		return pingLatencyUDP;
	}
	
	/**
	 * Gets the current TCP ping latency.
	 * @return latency (ms).
	 */
	public double getTCPPingLatency() {
		return pingLatencyTCP;
	}
	
	/**
	 * Checks if the UDP ping wasn't returned.
	 * @return true if ping not returned.
	 */
	public boolean getNoReturnUDP() {
		return noReturnUDP;
	}
	
	/**
	 * Checks if the TCP ping wasn't returned.
	 * @return true if ping not returned.
	 */
	public boolean getNoReturnTCP() {
		return noReturnTCP;
	}
	
	/**
     * Starts the ping thread.
     */
    private void start() {
        if ((pingThread == null) || !run) { 
            pingThread = new Thread(this, "ping thread");
            pingThread.start();
        }
    }
    
    @Override
    public void run() {
    	run = true;
        while (run) {
            try {
                Thread.sleep(SLEEP_TIME);
            } 
            catch (InterruptedException e) {}
        	
            ServiceCommunication comm = getServiceCommunication();
            
            // Check if pings were not returned.
            if (!completedPingUDP && (pingLatencyUDP > PING_TIMEOUT)) noReturnUDP = true;
            if (!completedPingTCP && (pingLatencyTCP > PING_TIMEOUT)) noReturnTCP = true;
            
            //System.out.println("Sending ping service posts");
    		pingStartTime = (double) System.nanoTime() / 1000000D;
            
    		// Send UDP ping post.
        	try {
        		completedPingUDP = false;
        		comm.sendServicePost(SERVICE_ID, PING.getBytes(), ServiceCommunication.UDP);
        	}
        	catch (Exception e) {
        		e.printStackTrace(System.err);
        	}
        	
        	// Send TCP ping post.
        	try {
        		completedPingTCP = false;
        		comm.sendServicePost(SERVICE_ID, PING.getBytes(), ServiceCommunication.TCP);
        	}
        	catch (Exception e) {
        		e.printStackTrace(System.err);
        	}
        	
        	// Change comm type if ping not returned.
        	/*
        	if (comm.getCommType() == ServiceCommunication.UDP) {
        		if (noReturnUDP && !noReturnTCP) {
        		    System.out.println("Changing from UDP to TCP in service comm due to echo timeout.");
        			comm.unsubscribeServices();
        			comm.setCommType(ServiceCommunication.TCP);
        			comm.subscribeServices();
        		}
        	}
        	else {
        		if (noReturnTCP && !noReturnUDP) {
        		    System.out.println("Changing from TCP to UDP in service comm due to echo timeout.");
        			comm.unsubscribeServices();
        			comm.setCommType(ServiceCommunication.UDP);
        			comm.subscribeServices();
        		}
        	}
        	*/
        }
    }

    @Override
    public String getType() {
        return TYPE;
    }
}